package rpc.test;

import java.util.List;
import java.util.Random;

/**
 * Created by zhangyanfei on 2019/7/2.
 * 随机加权平均
 *
 * @author zhangyanfei
 * @date 2019/07/02
 */
public class RandomLoadBalance {

    List<Invokers> invokersList;

    private Random random = new Random();

    RandomLoadBalance(List<Invokers> invokersList) {
        this.invokersList = invokersList;
    }

    public Invokers doSelect() {
        int size = invokersList.size();
        int totalWeight = 0;
        // 是否所有权重都相同
        boolean sameWeight = true;

        for (int i = 0; i < size; i++) {
            int weight = invokersList.get(i).weight;
            totalWeight += weight;
            if (sameWeight && i > 0 && weight != invokersList.get(i - 1).weight) {
                sameWeight = false;
            }
        }
        // 加权随机算法
        if (totalWeight > 0 && !sameWeight) {
            int offset = random.nextInt(totalWeight);
            for (int i = 0; i < size; i++) {
                offset -= invokersList.get(i).weight;
                if (offset < 0) {
                    return invokersList.get(i);
                }
            }
        }
        return invokersList.get(random.nextInt(size));
    }

}
